<template>
    <div style="background-color: rgb(241, 241, 241);padding:5px;padding-right: 7px;min-height: 100vh;box-sizing: border-box;">
        <van-nav-bar :title="$route.query.addressInfo ? '编辑地址' : '新增地址'" left-text="返回" left-arrow fixed @click="$router.back">
        </van-nav-bar>
        <div style="height: 50px;"></div>

        <van-address-edit :area-list="areaList" show-set-default :address-info="addressList" :show-delete="!!$route.query.addressInfo"
            :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" />

    </div>
</template>

<script setup>
import { areaList } from '@vant/area-data'
import { watch, ref } from 'vue'
import { getAddressList, addAddress, delAddress, editAddress } from '@/api/index.js'
import { showToast } from 'vant';
import { useRouter, useRoute } from 'vue-router'

let value = ref()
let route = useRoute()
let router = useRouter()

let addressList = ref() //用来数据回显

if (route.query.addressInfo) {

let addressData = JSON.parse(decodeURI(atob(route.query.addressInfo)))
 //console.log(addressData)
addressList.value = {
    name: addressData.name, province: addressData.province, city: addressData.city,
    tel: addressData.phone, county: addressData.town,id:addressData.id,
    addressDetail: addressData.detail, isDefault: addressData.is_default ? true : false
}
}
    //判断query是否有参数 有就编辑 没有就添加
let onSave = async (data) => {
    let params = {
        is_default: data.isDefault ? 1 : 0,
        name: data.name,
        phone: data.tel,
        province: data.province,
        city: data.city,
        town: data.county,
        street: 'null',
        detail: data.addressDetail
    }

    if (route.query.addressInfo) {
        console.log(data)
        let res = await editAddress({
            ...params,id:data.id
        })
        if (res.code == 1) {
            showToast({
                message: '编辑成功',
                duration: 300
            })
          
        }

    } else {
        let res = await addAddress(params)
        if (res.code == 1) {
            showToast({
                message: '添加成功',
                duration: 300
            })
        }
    }
    router.replace({
        path:'/address',
        query:{
            orderInfo:route.query.orderInfo
        }
    })
}

function onDelete(data){
    
   delAddress({id:data.id}).then(res=>{
    if(res.code==1){
        showToast({
                message: '删除成功',
                duration: 300
            })
    }
    router.replace({
        path:'/address',
        query:{
            orderInfo:route.query.orderInfo
        }
    })
})
}


</script>